package com.itheima.service.impl;

import com.itheima.pojo.OrderSetting;
import com.itheima.mapper.OrdersettingMapper;
import com.itheima.pojo.OrderSettingVO;
import com.itheima.service.IOrdersettingService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.YearMonth;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author author
 * @since 2024-12-21
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class OrdersettingServiceImpl extends ServiceImpl<OrdersettingMapper, OrderSetting> implements IOrdersettingService {
    @Autowired
    private OrdersettingMapper ordersettingMapper;

    @Override
    public List<OrderSettingVO> getOrderSettingByMonth(String month) {
        String[] split = month.split("-");
        int year = Integer.parseInt(split[0]);
        int month1 = Integer.parseInt(split[1]);
        YearMonth yearMonth = YearMonth.of(year, month1);
        LocalDate start = yearMonth.atDay(1);
        LocalDate end = yearMonth.atEndOfMonth();
        List<OrderSetting> list = ordersettingMapper.getOrderSettingByMonth(start, end);
        List<OrderSettingVO> list1 = new ArrayList<>();
        for (OrderSetting orderSetting : list) {
            OrderSettingVO orderSettingVO = new OrderSettingVO();
            // 将 Date 转换为 LocalDate
            LocalDate orderLocalDate = orderSetting.getOrderDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
            orderSettingVO.setDate(String.valueOf(orderLocalDate.getDayOfMonth())); // 获取日部分
            orderSettingVO.setNumber(orderSetting.getNumber());
            orderSettingVO.setReservations(orderSetting.getReservations());
            list1.add(orderSettingVO);
        }
        return list1;
    }



    @Override
    public void createOrUpdate(OrderSetting orderSetting) {
        orderSetting.setReservations(0);
        if (ordersettingMapper.countNumberByOrderDate(orderSetting.getOrderDate()) > 0){
            ordersettingMapper.editNumberByOrderDate(orderSetting);
        }else {
            ordersettingMapper.add(orderSetting);
        }

    }
}
